package com.addict.applocker.manager;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;

import com.addict.applocker.Data.AppListItem;
import com.addict.applocker.activity.MainActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Objects;

/**
 * 管理冻结软件数据类
 * - 内部使用file保存软件包名的方式保存数据
 * - 之所以没有用SQLite，是因为可能会经常插入删除
 * - 而数据库查询的优势却又用不到
 */
public class IceFileDataManager {
    // 换种方式实现单例，纯静态类，目前只是觉得在编写上不友好
    // - 16/4/19 ：使用上面有点不友好，很多参数可以集成在类里面，下一版本准备替换
    // 等待问题出现中...
    private final static String DATA_PATH = "AppData.dat";

    private static ArrayList<AppListItem> mDataArray = new ArrayList<AppListItem>();

    public static void read(final Context context, final Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                readData(context);
                handler.sendEmptyMessage(MainActivity.ON_READDATA_END);
            }
        }).start();
    }

    public static void save(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                saveData(context);
            }
        }).start();
    }

    public static ArrayList<AppListItem> getData() {
        synchronized (mDataArray) {
            return mDataArray;
        }
    }

    private static void readData(Context context) {
        synchronized (mDataArray) {
            mDataArray.clear();
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(context.openFileInput(DATA_PATH)));
                PackageManager pm = context.getPackageManager();

                String line = null;
                while((line = in.readLine()) != null) {
                    String[] formatStr = line.split(" ");
                    if (formatStr.length != 2) continue; // 读取的数据出错，继续下一条

                    try {
                        ApplicationInfo info = pm.getApplicationInfo(formatStr[1], PackageManager.GET_META_DATA);

                        String name = pm.getApplicationLabel(info).toString();
                        Drawable icon = info.loadIcon(pm);
                        Boolean start = Integer.valueOf(formatStr[0]) == 0 ? false : true;
                        AppListItem item = new AppListItem(name, formatStr[1], icon, start);

                        mDataArray.add(item);
                    } catch (PackageManager.NameNotFoundException e) {
                        Log.e("Debug", "没有找到指定的软件:" + formatStr[1]);
                        continue;
                    }
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void saveData(Context context) {
        synchronized (mDataArray) {
            FileOutputStream out = null;
            try {
                out = context.openFileOutput(DATA_PATH, Context.MODE_PRIVATE);

                for(int i = 0; i < mDataArray.size(); i++) {
                    AppListItem item = mDataArray.get(i);
                    String temp = String.valueOf(item.isStart() ? 1 : 0) + " " + item.getAppPackageName() + "\n";
                    out.write(temp.getBytes());
                    out.flush();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(out != null) out.close();
                } catch (IOException e) {}
            }
        }
    }
}
